#include "transcoder_core.h"

EncodeStruct ess[6];
int OUTPUT_VIDEO_NUM;
int PRINT_DYNAMIC_FPS;
int GOP_COUNT;
int HAS_AUDIO;
char* SRC_FILENAME;
int DELAY;

float total_frame_cnt;
float total_fps_cnt; 

inline void atomic_inc(int *var, int m, sem_t *lock)
{
	sem_wait(lock);
    (*var) += m; 
	sem_post(lock);
}

inline void atomic_dec(int *var, int m, sem_t *lock)
{
	sem_wait(lock);
    (*var) -= m;
	sem_post(lock);
}

void print_average_fps()
{
    float encoded_frame_cnt = 0;

    for (int i = 0; i < OUTPUT_VIDEO_NUM; i++)
    {
        sem_wait(&ess[i].thread_cnt_mutex);
        encoded_frame_cnt += ess[i].encoded_frame_cnt;
        ess[i].encoded_frame_cnt = 0;
        sem_post(&ess[i].thread_cnt_mutex);
    }

    if (PRINT_DYNAMIC_FPS)
    {
        /*float average_fps = encoded_frame_cnt / OUTPUT_VIDEO_NUM;*/
        int average_fps = encoded_frame_cnt / OUTPUT_VIDEO_NUM;
        /*printf("FPS : %.2f\n", average_fps);*/
        printf("FPS : %d\n", average_fps + 1);
        
        total_fps_cnt += 1;
        total_frame_cnt += average_fps;
    }
}

void output_video(EncodeStruct *es)
{
	char* command = xcalloc(GOP_COUNT, 64);
	char buf[128];
	strcpy(command, "MP4Box");
	int i = 0;
	for (i = 0; i < GOP_COUNT; i++) {
        sprintf(buf, " -cat ./%s/%d.%s", es->output_dir, i, es->output_format);
		strcat(command, buf);
	}

    /*
	 *sprintf(buf, " -cat ./%s/flush.%s", es->output_dir, es->output_format);
	 *strcat(command, buf);
     */

	sprintf(buf, " -new %s", es->output_filename);
	strcat(command, buf);
	system(command);

	sprintf(command, "rm -rf %s", es->output_dir);
	system(command);

	if(HAS_AUDIO){
		sprintf(command, "/usr/local/bin/MP4Box -sbr -add %s#audio -add %s#video -delay 1=%d -new %s", SRC_FILENAME, es->output_filename, DELAY, es->output_filename);
		system(command);
	}
}
